// pages/order/payOrder/payOrder.js
var _ajax = require('../../../utils/httpUtil.js');
var _map = require('../../../utils/map.js');
var _login = require('../../../utils/login.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        payInfo: {},
        peiPre: 0,
        phone: "",
        allPrice: 0,
        totalJian: 0,
        shopInfo: {
            title: '',
            baoPre: 0,
            manjian: 0,
        },
        obj: {
            province: '',
            city: '',
            area: '',
            addressInfo: '',
            userName: '',
            mobilePhone: '',
            addrId: "",
            lat: "",
            lng: "",
        },
        foodsArr: [],
        canNum: '未选择',
        typeArr: ['未选择', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
        typeIndex: 0,
        noAddress: false,
        shadowFlag: false,
        beizhu: '口味、偏好等要求',
        payType: 1,
        actList: [], //活动列表
        isRoom: 1, //1 外卖 2堂食
        canNumRoom: 0, //堂食就餐人数
        tabTitle: '', //桌台名称
        tabId: '', //桌台id
        tabPrice: '', //餐具费
        showPayType: 0,
        disPayBtn: 0, //1=禁用

    },
    getInfo() {

    },
    bindViewEvent: function(e) {
        console.log(e);
        this.setData({
            canNum: e.detail.value == 0 ? '未选择' : e.detail.value,
            typeIndex: e.detail.value
        })
        wx.setStorage({
            key: 'orderCanNum-' + wx.getStorageSync("orderShopId"),
            data: {
                canNum: e.detail.value == 0 ? '未选择' : e.detail.value,
                typeIndex: e.detail.value
            }
        })
    },
    radioChange: function(e) {
        console.log('radio发生change事件，携带value值为：', e.detail.value)
        this.setData({
            payType: e.detail.value
        })
    },
    addBeizhu() {
        wx.setStorageSync('pageStatus', 2);
        if (this.data.beizhu == '口味、偏好等要求') {
            wx.navigateTo({
                url: '../beizhu/beizhu?text= ',
            })
        } else {
            wx.navigateTo({
                url: '../beizhu/beizhu?text=' + this.data.beizhu,
            })
        }
    },
    //获取默认的收货地址 ,
    getDefAddress: function(id) {
        var _this = this;
        var mm = {};
        if (id) {
            mm.id = id;
        } else {
            //如果不是地址列表返回的时候,先去查询缓存
            var sss = wx.getStorageSync("orderShopId");
            console.log(sss);
            var ords = wx.getStorageSync("orderAddress-" + wx.getStorageSync("orderShopId"));
            console.log(ords);
            if (ords) {
                _this.setData({
                    obj: ords
                });
                return;
            }

        }
        mm.userId = wx.getStorageSync("uid");
        console.log(mm);
        _ajax.reqPost('xwx/getUserAddressList', mm, function(res) {
            console.log(res);
            if (!res.returnObject) {
                _this.setData({
                    noAddress: true
                })
            }
            var li = res.returnObject.list;
            for (var i = 0; i < li.length; i++) {
                if (id || li[i].isDefault == 1) {
                    var l = li[i];
                    console.log(l);
                    _this.setData({
                        obj: {
							province: '',
							city: '',
							area: '',
							addressInfo: l.province + l.city + l.area + l.addressInfo,
                            userName: l.userName,
                            addrId: l.id,
                            mobilePhone: l.mobilePhone,
                            lat: l.latitude,
                            lng: l.longitude
                        }
                    }, () => {
                        wx.setStorage({
                            key: 'orderAddress-' + wx.getStorageSync("orderShopId"),
                            data: _this.data.obj
                        })
						_this.showOrderInfo(wx.getStorageSync('orderShopId'));
                    });

                    break;
                }
            }
        });
    },
    /**
     * 打电话 
     */
    linkShop: function(e) {
        console.log(e);
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone, //此号码并非真实电话号码，仅用于测试
            success: function() {
                console.log("拨打电话成功！")
            },
            fail: function() {
                console.log("拨打电话失败！")
            }
        });
    },
    goChooseAddr: function() {
        wx.setStorageSync('pageStatus', 2);
        wx.navigateTo({
            url: '../../self/myAddress/myAddress?isOrdCho=1',
        })
    },
    /**
     * 选择好支付方式后开始去拉取收银台
     */
    toPayOk: function() {
		wx.showLoading({
			title: '',
			mask: true
		})
        if (this.data.disPayBtn == 1) {
            return;
        }
        this.setData({
            disPayBtn: 1
        })
        var _this = this;
        var ss = this.data.payType;
        console.log(ss);
        var pay = this.data.payInfo;
		let user = wx.getStorageSync('user');
		if (wx.getStorageSync('uid') && user && user.id == wx.getStorageSync('uid')) {
			pay.userId = wx.getStorageSync('uid');
		} else {
			_login.loginx(this, function () {
				this.toPayOk();
			});
		}

		pay.latitude = this.data.obj.lat;
		pay.longitude = this.data.obj.lng;

		pay.userName = this.data.obj.userName;
		pay.userPhone = this.data.obj.mobilePhone;
		pay.userAddress = this.data.obj.addressInfo;

        pay.payType = ss;
        var shopId = wx.getStorageSync('orderShopId');
        var mark = wx.getStorageSync('orderbeizhu-' + shopId);
        console.log(mark);
        var can = wx.getStorageSync('orderCanNum-' + shopId);
        var peo = wx.getStorageSync('people');

		//选择的餐具数量
		console.log(can.canNum );

        pay.mark = mark + (this.data.isRoom == 1 ? ((can.canNum && can.canNum != 0&& can.canNum!='未选择') ? '$&#$' + can.canNum : '') : (peo ? '$&#$' + peo.split('-')[0] : ''));
        //判断是否是堂食订单
		console.log(pay);
        if (wx.getStorageSync('tangshi') != 1) {
            pay.userName = wx.getStorageSync('zhuoID'); //桌台id
            pay.userAddress = wx.getStorageSync('zhuoTitle'); //桌台标题
        }
        //创建订单并支付
        console.log(pay);
        _ajax.reqPost('xorder/createOrdersInfo', pay, function(data) {
            console.log(data);
		
            if (data.resultCode == 1000) {
                if (ss == 1) { //微信支付
                    wx.requestPayment({
                        timeStamp: data.returnObject.timestamp,
                        nonceStr: data.returnObject.noncestr,
                        package: data.returnObject.wxpackage,
                        signType: 'MD5',
                        paySign: data.returnObject.paySign,
                        success(res) {
                            console.log(res);
                            wx.showToast({
                                title: '支付成功',
                                icon: 'success',
								mask:true,
                                duration: 2000
                            });
                        },
                        fail(res) {
                            wx.showToast({
                                title: '支付失败',
                                icon: 'loading',
								mask: true,
                                duration: 2000
                            });
                        },
                        complete(res) {
                            //跳往订单列表
                            setTimeout(function() {
                                wx.switchTab({
                                    url: '/pages/order/orderList/orderList', //注意switchTab只能跳转到带有tab的页面，不能跳转到不带tab的页面
                                    success: function(e) { //跳转成功后刷新页面
                                        //清除缓存
                                        wx.removeStorage({
											key: 'orderInfo-' + wx.getStorageSync('orderShopId') + '-' + _this.data.isRoom,
                                            success(res) {
                                                console.log(res.data)
                                            }
                                        })
                                        //清除缓存
                                        wx.removeStorage({
											key: 'orderAddress-' + wx.getStorageSync('orderShopId'),
                                            success(res) {
                                                console.log(res.data)
                                            }
                                        })
										//清除缓存
										wx.removeStorage({
											key: 'orderbeizhu-' + wx.getStorageSync('orderShopId'),
											success(res) {
												console.log(res.data)
											}
										})
										//清除缓存
										wx.removeStorage({
											key: 'orderCanNum-' + wx.getStorageSync('orderShopId'),
											success(res) {
												console.log(res.data)
											}
										})
                                    }
                                })
                            }, 2000)

                        }

                    })
                } else {
                    setTimeout(function() {
                        wx.switchTab({
                            url: '/pages/order/orderList/orderList', //注意switchTab只能跳转到带有tab的页面，不能跳转到不带tab的页面
                            success: function(e) { //跳转成功后刷新页面
                                //清除缓存
                                wx.removeStorage({
									key: 'orderInfo-' + wx.getStorageSync('orderShopId') + '-' + _this.data.isRoom,
                                    success(res) {
                                        console.log(res.data)
                                    }
                                })
                                //清除缓存
                                wx.removeStorage({
                                    key: 'orderAddress-' + wx.getStorageSync('orderShopId'),
                                    success(res) {
                                        console.log(res.data)
                                    }
                                })
								//清除缓存
								wx.removeStorage({
									key: 'orderbeizhu-' + wx.getStorageSync('orderShopId'),
									success(res) {
										console.log(res.data)
									}
								})
								//清除缓存
								wx.removeStorage({
									key: 'orderCanNum-' + wx.getStorageSync('orderShopId'),
									success(res) {
										console.log(res.data)
									}
								})
                            }
                        })
                    }, 1000)
                }
				wx.hideLoading();
            } else {
                _this.setData({
                    disPayBtn: 0
                })
				wx.showToast({
					title: data.returnObject,
					icon:'none',
					duration: 2000
				});
            }
        })
    },

    showOrderInfo: function(shopId) {
		wx.showLoading({
			title: '',
		})
        var payInfo = {};
        if (!shopId) {
            shopId = wx.getStorageSync('orderShopId');
        }
        payInfo.shopId = shopId;
		
        payInfo.sendType = 1;

     
        var pe = wx.getStorageSync('people');
        var pes = pe.split('-');

        var totalPrice = 0;
        console.log(shopId);
        var _this = this;
        wx.getStorage({
			key: 'orderInfo-' + shopId + '-' + this.data.isRoom,
            success: function(res) {
                var ord = res.data;
                console.log(ord);
                var _data = _this.data;
                //开始处理订单信息
                _ajax.reqPost('/xshop/getShopById', {
                    id: shopId,
                    longitude: _data.obj.lng,
                    latitude: _data.obj.lat
                }, function(res) {
                    if (res.resultCode == 1000) {
                        var dd = res.returnObject;
                        console.log(dd);
                        if (dd) {
                            totalPrice += Number(dd.shopSendPrice);
                            payInfo.sendPrice = dd.shopSendPrice;
                            _this.setData({
                                peiPre: (dd.shopSendPrice / 100).toFixed(2),
                                phone: dd.userContact
                            })
                        }
						//保存当前店铺的类型 
						_this.setData({
							shopType:dd.shopType,
						})

                        var shopInfo = {};
                        shopInfo.title = ord.shopTitle;
                        shopInfo.baoPre = (ord.packPrice / 100).toFixed(2); //包装费
						shopInfo.sendDis = dd.shopSendDistance; //配送距离
						shopInfo.lat = dd.latitude;
						shopInfo.lng = dd.longitude;
                        payInfo.packPrice = ord.packPrice;
                        payInfo.shopTitle = ord.shopTitle;
						totalPrice += ord.packPrice;
                        //计算活动优惠价格
                        var allJian = 0; //总共优惠的价格
                        var actLis = [];
                        var actLi;
                        var act = ord.activityids;
                        console.log(act);
                        if (act) {

                            payInfo.activityIds = act;

                            var actSplit = act.split(",");
                            console.log(actSplit);
                            for (var i = 0; i < actSplit.length; i++) {
                                actLi = {};
                                var s = actSplit[i].split("-");
                                console.log(s);
                                actLi.type = s[0];
                                actLi.price = ((Number(s[1])) / 100).toFixed(2);
                                switch (Number(s[0])) {
                                    case 1:
                                        actLi.icon = '/img/order/new.png';
                                        actLi.title = '新客立减';
                                        break;
                                    case 2:
                                        actLi.icon = '/img/order/minus.png';
                                        actLi.title = '满减活动';
                                        break;
                                    case 3:
                                        actLi.icon = '/img/order/discount.png';
                                        actLi.title = '单品折扣';
                                        break;
                                    case 4:
                                        actLi.icon = '/img/order/minus.png';
                                        actLi.title = '满减活动';
                                        break;
                                    case 5:
                                        actLi.icon = '/img/order/discount.png';
                                        actLi.title = '堂食折扣';
                                        break;
                                }
                                allJian += Number(s[1]);
                                actLis.push(actLi);
                                console.log(actLis);
                            }
                        }
                        //解析商品列表
                        var foodsArr = [];
                        var gli;
                        var gList = ord.goodsList;
                        var goodsIds = [];
                        var goodsIdss = "";
                        console.log(gList);
                        // for (var i = 0; i < gList.length; i++) {
							
                        for (var key in gList) {

                            gli = {}
                            goodsIdss = "";
                            var _d = gList[key];
                            console.log(_d);
							_d.id = _d.id.split('_')[0];
                            gli.img = _d.goodsPic.indexOf('../') >= 0 ? _d.goodsPic.replace('../', '/pages/') : _d.goodsPic;
                            gli.id = _d.id;
                            var out = wx.getStorageSync('tangshi');
                            console.log(out);
                            payInfo.type = out;
                            goodsIdss += _d.id;
                            gli.goodsName = _d.goodsTitle;
                            gli.goodsNum = _d.cnum;
                            gli.goodsPrice = Number(out == 1 ? _d.priceOut : _d.priceRoom) * _d.cnum;
                            //判断规格
                            var spList = _d.specList;
                            // for (var k = 0; k < spList.length; k++) {

                            // 	if (spList[k].num === 0){
                            // 		continue;
                            // 	}

                            //     if (spList.length > 1) {
                            //         gli.goodsName += "(" + spList[k].title + ")";
                            //     }
                            // gli.goodsNum = spList[k].num;
                            // gli.goodsPrice = (spList[k].totalPrice / 100).toFixed(2);
                            // totalPrice += Number(spList[k].totalPrice);
                            // gli.specId = spList[k].specId;
                            // gli.price = spList[k].price;
                            foodsArr.push(gli);
							
							var actids = ((key.split('_').length >1) ? key.split('_')[1] : 0);
							if(actids == 0 ){
								actids = spList[0].id;
							}
							goodsIdss += "-" + _d.cnum + "-" + (out == 1 ? _d.priceOut * 100 : _d.priceRoom * 100) + "-" + gli.goodsName + "-" +actids ;
                            //}
                            if (goodsIdss) {
                                goodsIds.push(goodsIdss);
                            }
                        }
                        payInfo.goodsIds = goodsIds;
                        var al = 0;
                        var oo = wx.getStorageSync('tangshi');
						
                        if (oo == 1) {
                            al = (Number(ord.totalPrice) + (Number(_this.data.peiPre) * 100)).toFixed(0);
                        } else {
							var ppo = wx.getStorageSync('people').split('-')[1];
							if(ppo){
								payInfo.packPrice = ppo;
                           		al = (Number(ord.totalPrice + Number(wx.getStorageSync('people').split('-')[1]))).toFixed(0);
							}else{
								al = (Number(ord.totalPrice));
							}
                        }
                        //显示商品信息
						payInfo.payPrice = al < 0 ? 0 : al;
                        _this.setData({
                            actList: actLis, //活动列表
                            shopInfo: shopInfo, //店铺信息
                            foodsArr: foodsArr, //商品列表
                            totalJian: (allJian / 100).toFixed(2), //总优惠价格
                            allPrice: ((al<0?0:al) / 100).toFixed(2), //小计
                            payInfo: payInfo
                        })
						wx.hideLoading();
                    }
                })
            }

        })
		
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        wx.setStorageSync('pageStatus', 1);
        var _this = this;
        console.log(options);
        //接受点击去结算按钮传来的店铺id
        if (options) {
            var shopId = options.shopId;
            console.log(shopId);
            if (shopId) {
                wx.setStorageSync("orderShopId", shopId);
            } else {
                shopId = wx.getStorageSync("orderShopId");
            }
        }
        var beizhu = options.beizhu;
        //获取当前店铺的付款方式
        this.getPayType();

        var peo = wx.getStorageSync('people').split('-')[1];
        //回显备注
        if (beizhu) {
            this.setData({
                beizhu: beizhu
            })
            wx.setStorage({
                key: 'orderbeizhu-' + shopId,
                data: beizhu
            })
        } else {
            //如果路径里面没有携带备注信息, 则去缓存获取, 缓存也没有的话就是重新添加
            var bz = wx.getStorageSync("orderbeizhu-" + shopId);
            if (bz) {
                this.setData({
                    beizhu: bz
                })
            }
        }
        //判断当前页面是堂食订单 还是外卖订单
        var typePayCac = wx.getStorageSync("tangshi");
        _this.setData({
            isRoom: typePayCac
        })
        if (typePayCac == 2) {
            //获取堂食订单里面的就餐人数 ,堂食设置了不收取餐具费, 则不显示餐具费的计算
            _this.setData({
                isRoom: 2, //1 外卖 2堂食
                canNumRoom: wx.getStorageSync('people').split('-')[0], //堂食就餐人数
                tabTitle: wx.getStorageSync('zhuoTitle'), //桌台号
                tabPrice: peo ? (peo / 100).toFixed(2) : 0,
            })
        }
        //先判断这个页面是否有选择的地址跳转参数
        let addrId = options.addrId;
        console.log(addrId);
        this.getDefAddress(addrId);
        //渲染缓存中的餐具数量
        console.log(shopId);
        wx.getStorage({
            key: 'orderCanNum-' + shopId,
            success: function(res) {
                _this.setData({
                    canNum: res.data.canNum,
                    typeIndex: res.data.typeIndex
                })
            },
        })
        //每次进来都需要解析前一个去结算页面放进缓存的值, 直到支付的时候,成功或者失败都要清空这个缓存
        this.showOrderInfo(shopId);


    },
	getUserInfo: function (e) {
		console.log(123);
		var that = this;		
		let user = wx.getStorageSync('user');
		if (wx.getStorageSync('uid') && user && user.id == wx.getStorageSync('uid')){
			//this.toPay();
		}else{
			_login.loginx(this, function () {
				console.log(111);
				that.toPay();
			});
		}
	},
    toPay() {
		
		var _this = this;
		var uid = wx.getStorageSync("uid");
		console.log(uid);
		if(!uid){
			
			return;
		}

        var bz = this.data.beizhu;
        console.log(bz);
        var bzz = wx.getStorageSync("orderShopId");
        console.log(bzz);
        if ('口味、偏好等要求' != bz) {
            wx.setStorageSync('orderbeizhu-' + bzz, bz);
        }
        var ss = wx.getStorageSync('tangshi');
        if (ss == 1) {
            var ainfo = this.data.obj.addressInfo;
            if (ainfo) {
				//判断当前选择的地址是否在商家的配送范围内
				var ainf = this.data.obj;
				console.log(ainf);
				var shopi = this.data.shopInfo;
				var dis = _map.getDistance(ainf.lat,ainf.lng,shopi.lat,shopi.lng);
				console.log(dis);
				if((dis/1000)>shopi.sendDis){
					console.log('当前地址不再配送范围内');
					wx.showToast({
						title: '当前收货地址不在商家的配送范围内，商家配送范围：'+shopi.sendDis+' km，请重新选择',
						icon: 'none',
						duration: 2000
					});
					return;
				}
                this.setData({
                    shadowFlag: true
                })
            } else {
                wx.showToast({
                    title: '请选择收货地址',
                    icon: 'none',
                    duration: 2000
                });
            }
        } else {
            this.setData({
                shadowFlag: true
            })
        }

    },
    closePay() {
        this.setData({
            shadowFlag: false
        })
    },
    closePayMent() {
        this.setData({
            shadowFlag: false
        })
    },
    getPayType() {
        //getShopSetBySID
        var _this = this;
        _ajax.reqPost('xshop/getShopSetBySID', {
            shopId: wx.getStorageSync('orderShopId')
        }, function(res) {
            console.log(res);
            if (res.resultCode == 1000) {
                if (res.returnObject) {
                    var d = res.returnObject;
                    var typePayCac = wx.getStorageSync("tangshi");
                    console.log(typePayCac);
                    var pt = 1;
                    if (typePayCac == 1) { //外卖付款方式
                        if (d.payTypeOut == 2) {
                            pt = 2;
                        }
                        console.log(_this.data.showPayType);
                        console.log(d.payTypeOut);
                        console.log(d.payType);
                        _this.setData({
                            showPayType: d.payTypeOut,
                            payType: pt
                        })
                    } else {
                        if (d.payType == 2) {
                            pt = 2;
                        }
                        //堂食付款方式
                        _this.setData({
                            showPayType: d.payType,
                            payType: pt
                        })
                    }
                }
            }
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        // var ps = wx.getStorageSync('pageStatus');
        // console.log(getCurrentPages());

        // if(ps == 1){
        // 	// getCurrentPages();
        // 	wx.navigateTo({
        // 		url: '/pages/shopInfo/shopInfo?' + (wx.getStorageSync('tangshi') == 1 ?'shopId='+ wx.getStorageSync('orderShopId') :'scene='+ (wx.getStorageSync('zhuoID') + '-' + wx.getStorageSync('orderShopId'))),
        // 		fail:function(e){
        // 			console.log(e);
        // 		},
        // 		success:function(e){
        // 			console.log(e);
        // 		}
        // 	})
        // 	console.log(123);

        // }else{
        // 	wx.setStorageSync('pageStatus',1);
        // }
        // console.log(123);

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})